<template>
  <div id="stocks">
    <el-row :gutter="20">
      <el-col :span="13">
        <div class="grid-content bg-purple-dark">
          <el-card class="box-card">
            <!-- 为 ECharts 准备一个具备大小（宽高）的 DOM -->
            <div id="columnar" style="width: 650px;height:350px;"></div>
          </el-card>
          <el-card class="box-card" style="margin-top:10px;">
            <!-- 库存饼图 -->
            <div id="circular" style="width: 590px;height:225px;"></div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="11">
        <div class="grid-content bg-purple-dark">
          <el-card class="box-card">
            <!--查询条件-->
            <el-form size="mini" :inline="true" :model="queryMap" class="demo-form-inline">
              <el-form-item>
                <el-cascader
                  placeholder="请选择分类查询"
                  @change="selectChange"
                  v-model="categoryKeys"
                  :props="searchSelectProps"
                  :options="catetorys"
                  clearable
                ></el-cascader>
              </el-form-item>

              <el-form-item>
                <el-input clearable="" @clear="search" v-model="queryMap.name" placeholder="物资名称"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button size="mini" type="primary" @click="search" icon="el-icon-search">查询</el-button>
              </el-form-item>
            </el-form>

            <!--表格区域-->
            <el-table height="530" border :data="tableData" style="width: 100%">
              <el-table-column prop="imageUrl" label="图片" align="center" width="80" padding="0px">
                <template slot-scope="scope">
                  <el-popover placement="right" trigger="hover">
                    <el-image :src="scope.row.imageUrl" style="width: 200px;height: 200px">
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                    <el-image slot="reference" :src="scope.row.imageUrl" :alt="scope.row.imageUrl"
                              style="height: 32px;width: 32px;cursor: pointer">
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="名称" width="140"></el-table-column>
              <el-table-column prop="model" label="规格" width="120"></el-table-column>
              <el-table-column prop="stock" label="库存">
                <template slot-scope="scope">
                  <el-tag size="mini" closable>{{scope.row.stock}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位"></el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              style="margin-top:20px;"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="current"
              :page-sizes="[9, 10, 15, 20]"
              :page-size="size"
              layout="total, prev, pager, next, jumper,sizes"
              :total="total"
            ></el-pagination>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import echarts from 'echarts'
  import { getCategory } from '@/api/biz/productCategory'
  import { findProductStocks } from '@/api/biz/product'

  export default {
    data () {
      return {
        catetorys: [], //类别选择
        searchSelectProps: {
          expandTrigger: 'hover',
          value: 'id',
          label: 'name',
          children: 'children',
          checkStrictly: false,
          multiple: true,
          emitPath: false
        }, //级联搜索选择器配置项
        size: 6,
        total: 100,
        current: 1,
        tableData: [],
        queryMap: {
          name: '',
          categoryKeys: '',
          supplier: '',
          status: 0,
        }, //查询对象
        categoryKeys: [],//搜索类别
        xData: [],
        yData: [],
        legendData: [], //饼图存放物资名称
        selected: {}, //存放选择的数据
        seriesData: [{
          name: '',
          value: ''
        }] //饼图数据
      }
    },
    created () {
      this.getStockList()
      this.getCategory()
    },
    mounted: function () {
      this.draw()
      this.drawRound()
    },
    methods: {
      /**
       * 搜索
       */
      search () {
        this.current = 1
        this.getStockList()
      },
      /**
       * 加载库存信息
       */
      getStockList () {
        findProductStocks(this.current, this.size, this.queryMap).then(res => {
          if (res) {
            this.total = res.data.total
            this.tableData = res.data.records
            //条形图数据
            this.xData = []
            this.yData = []
            this.selected = {}
            //饼图数据
            this.legendData = []
            this.selected = {}
            this.seriesData = [{}]
            let $this = this
            //构建表格条形统计图的数据
            this.tableData.forEach(function (e) {
              //构建条形的数据对象
              $this.xData.push(e.name)
              $this.yData.push(e.stock)
              //构建饼图的数据对象
              $this.legendData.push(e.name)
              $this.seriesData.push({
                name: e.name,
                value: e.stock
              })
            })
            //重新绘制表格
            this.draw()
            //重新绘制表格
            this.drawRound()
          }
        })
      },

      //当每页条数改变
      handleSizeChange (val) {
        this.size = val
        this.getStockList()
      },

      //当前页码改变
      handleCurrentChange (val) {
        this.current = val
        this.getStockList()
      },

      /**
       * 绘制条形统计图
       */
      draw () {
        let myChart = echarts.init(document.getElementById('columnar'))
        // 指定图表的配置项和数据
        let option = {
          title: {
            text: '库存条形图'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false }, //  缩放
              magicType: { type: ['bar'] }, ///　　折线  直方图切换
              restore: {}, // 重置
              saveAsImage: {} // 导出图片
            }
          },
          tooltip: {},
          legend: {
            data: ['库存量']
          },
          xAxis: {
            data: this.xData
          },
          yAxis: {},
          series: [
            {
              name: '库存量',
              type: 'bar',
              showBackground: true,
              data: this.yData,
              itemStyle: {
                normal: {
                  //好，这里就是重头戏了，定义一个list，然后根据所以取得不同的值，这样就实现了，
                  color: function (params) {
                    // build a color map as your need.
                    var colorList = [
                      '#0780cf ', '#fa6d1d ', '#ac2026 ', '#701866 ', '#d22e8d ',
                      '#FE8463', '#a195c5 ', '#FAD860', '#F3A43B', '#60C0DD',
                      '#D7504B', '#a195c5  ', '#F4E001', '#F0805A', '#63b2ee'
                    ]
                    return colorList[params.dataIndex]
                  },
                  //以下为是否显示，显示位置和显示格式的设置了
                  label: {
                    show: true,
                    position: 'top',
//                             formatter: '{c}'
                    formatter: '{b}\n{c}'
                  }
                }
              },
            },
          ]
        }

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option)
      },
      /**
       * 绘制饼图
       */
      drawRound () {
        const myChart = echarts.init(document.getElementById('circular'))
        const option = {
          title: {
            text: '库存占比图',

            left: 'left'
          },
          toolbox: {
            show: true,
            feature: {
              saveAsImage: {} // 导出图片
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: this.legendData,
            selected: this.selected
          },
          series: [
            {
              name: '物资名称',
              type: 'pie',
              radius: '55%',
              center: ['40%', '50%'],
              data: this.seriesData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        myChart.setOption(option)
      },

      /**
       * 分类搜索改变时
       */
      selectChange () {
        let str = ''
        for (let i = 0; i < this.categoryKeys.length; i++) {
          str += this.categoryKeys[i] + ','
        }
        str = str.substring(0, str.length - 1)
        this.queryMap.categoryKeys = str
        console.log(str)
      },

      /** 查询物资分类列表 */
      getCategory () {
        getCategory().then(res => {
          if (res) {
            this.catetorys = this.deleteNullChildren(res.data.menus)
          }
        })
      },
      //删除children为null的菜单的children属性
      deleteNullChildren (category) {
        for (let i = 0; i < category.length; i++) {
          if (category[i].children.length > 0) {						//判断children的数组长度
            this.deleteNullChildren(category[i].children)
          }
          if (category[i].children.length === 0) {
            category[i].children = undefined
          }
        }
        return category
      },
    },
  }
</script>
